// ResignationApproval.jsx 组件文件
import { Table, Button, Space, Modal, message, Tag, Card, Divider, Input, Avatar, Upload, Tabs } from '@/utils/antd-imports';
import { AuditOutlined, CheckOutlined, CloseOutlined, UserOutlined, SendOutlined, UploadOutlined } from '@/utils/icons';
import React, { useState } from 'react';








import Steps from 'antd/es/steps';




import { Comment } from '@ant-design/compatible';


const { TextArea } = Input;
const { TabPane } = Tabs;

const ResignationApproval = () => {
  const [approvalData, setApprovalData] = useState([
    {
      key: '1',
      employeeName: '张三',
      department: '技术部',
      position: '高级前端工程师',
      applyDate: '2025-09-15',
      lastWorkingDay: '2025-10-15',
      reason: '个人职业发展需要',
      status: 'pending',
      handoverPlan: '已完成项目文档交接，指定李四为工作交接人',
      approvalProcess: [
        { 
          title: '提交申请', 
          description: '张三', 
          date: '2025-09-15', 
          status: 'finish',
          comments: [
            {
              author: '张三',
              avatar: <Avatar icon={<UserOutlined />} />,
              content: <p>因个人职业发展需要，申请离职。</p>,
              datetime: '2025-09-15 09:00',
              attachments: []
            }
          ]
        },
        { 
          title: '部门审批', 
          description: '李经理', 
          date: '2025-09-16', 
          status: 'finish',
          comments: [
            {
              author: '李经理',
              avatar: <Avatar icon={<UserOutlined />} />,
              content: <p>已了解离职原因，建议人事部门安排面谈。</p>,
              datetime: '2025-09-16 10:30',
              attachments: [
                { name: '离职面谈记录.pdf', url: '#' }
              ]
            }
          ]
        },
        { 
          title: '人事审核', 
          description: '王HR', 
          date: '2025-09-17', 
          status: 'finish',
          comments: [
            {
              author: '王HR',
              avatar: <Avatar icon={<UserOutlined />} />,
              content: <p>已完成离职面谈，确认离职原因，工作交接计划合理。</p>,
              datetime: '2025-09-17 14:20',
              attachments: [
                { name: '离职交接清单.xlsx', url: '#' }
              ]
            }
          ]
        },
        { 
          title: '最终审批', 
          description: '等待朱泽名处理', 
          date: '', 
          status: 'process',
          comments: [],
          attachments: []
        }
      ]
    },
    {
      key: '2',
      employeeName: '李四',
      department: '市场部',
      position: '市场经理',
      applyDate: '2025-09-20',
      lastWorkingDay: '2025-10-20',
      reason: '家庭原因需回老家发展',
      status: 'approved',
      handoverPlan: '已完成客户资源交接，指定王五接替工作',
      approvalProcess: [
        { 
          title: '提交申请', 
          description: '李四', 
          date: '2025-09-20', 
          status: 'finish',
          comments: [
            {
              author: '李四',
              avatar: <Avatar icon={<UserOutlined />} />,
              content: <p>因家庭原因需回老家发展，申请离职。</p>,
              datetime: '2025-09-20 09:00',
              attachments: []
            }
          ]
        },
        { 
          title: '部门审批', 
          description: '张总监', 
          date: '2025-09-21', 
          status: 'finish',
          comments: [
            {
              author: '张总监',
              avatar: <Avatar icon={<UserOutlined />} />,
              content: <p>理解员工个人原因，建议人事部门做好工作交接安排。</p>,
              datetime: '2025-09-21 09:15',
              attachments: [
                { name: '客户交接清单.pdf', url: '#' }
              ]
            }
          ]
        },
        { 
          title: '人事审核', 
          description: '王HR', 
          date: '2025-09-22', 
          status: 'finish',
          comments: [
            {
              author: '王HR',
              avatar: <Avatar icon={<UserOutlined />} />,
              content: <p>已完成离职面谈，确认离职原因，工作交接计划合理。</p>,
              datetime: '2025-09-22 11:30',
              attachments: []
            }
          ]
        },
        { 
          title: '最终审批', 
          description: '朱泽名', 
          date: '2025-09-23', 
          status: 'finish',
          comments: [
            {
              author: '朱泽名',
              avatar: <Avatar icon={<UserOutlined />} />,
              content: <p>同意离职申请，请按计划完成工作交接。</p>,
              datetime: '2025-09-23 14:00',
              attachments: [
                { name: '离职审批表.pdf', url: '#' }
              ]
            }
          ]
        }
      ]
    }
  ]);

  const [selectedResignation, setSelectedResignation] = useState(null);
  const [commentText, setCommentText] = useState('');
  const [activeTab, setActiveTab] = useState('pending');
  const [fileList, setFileList] = useState([]);

  // 筛选不同状态的离职申请
  const pendingResignations = approvalData.filter(item => item.status === 'pending');
  const processedResignations = approvalData.filter(item => item.status !== 'pending');
  const myInitiatedResignations = approvalData.filter(item => item.employeeName === '张三'); // 假设当前用户是张三

  const handleApprove = () => {
    if (!selectedResignation) return;
    
    Modal.confirm({
      title: '确认审批通过',
      content: `确定要通过员工 "${selectedResignation.employeeName}" 的离职申请吗？`,
      onOk: () => {
        const newData = approvalData.map(item => 
          item.key === selectedResignation.key ? { 
            ...item, 
            status: 'approved',
            approvalProcess: item.approvalProcess.map((step, index) => 
              index === item.approvalProcess.length - 1 ? 
              { 
                ...step, 
                description: '朱泽名', 
                date: new Date().toISOString().split('T')[0], 
                status: 'finish',
                comments: [
                  ...step.comments,
                  {
                    author: '朱泽名',
                    avatar: <Avatar icon={<UserOutlined />} />,
                    content: <p>离职申请审批通过，请按计划完成工作交接。</p>,
                    datetime: new Date().toLocaleString(),
                    attachments: fileList.map(file => ({
                      name: file.name,
                      url: '#'
                    }))
                  }
                ]
              } : step
            )
          } : item
        );
        setApprovalData(newData);
        setSelectedResignation(newData.find(item => item.key === selectedResignation.key));
        setFileList([]);
        setCommentText('');
        message.success('离职申请已审批通过');
      }
    });
  };

  const handleReject = () => {
    if (!selectedResignation) return;
    
    Modal.confirm({
      title: '确认审批驳回',
      content: `确定要驳回员工 "${selectedResignation.employeeName}" 的离职申请吗？`,
      onOk: () => {
        const newData = approvalData.map(item => 
          item.key === selectedResignation.key ? { 
            ...item, 
            status: 'rejected',
            approvalProcess: item.approvalProcess.map((step, index) => 
              index === item.approvalProcess.length - 1 ? 
              { 
                ...step, 
                description: '朱泽名', 
                date: new Date().toISOString().split('T')[0], 
                status: 'error',
                comments: [
                  ...step.comments,
                  {
                    author: '朱泽名',
                    avatar: <Avatar icon={<UserOutlined />} />,
                    content: <p>离职申请驳回，请与部门负责人沟通。</p>,
                    datetime: new Date().toLocaleString(),
                    attachments: fileList.map(file => ({
                      name: file.name,
                      url: '#'
                    }))
                  }
                ]
              } : step
            )
          } : item
        );
        setApprovalData(newData);
        setSelectedResignation(newData.find(item => item.key === selectedResignation.key));
        setFileList([]);
        setCommentText('');
        message.warning('离职申请已驳回');
      }
    });
  };

  const showDetail = (record) => {
    setSelectedResignation(record);
  };

  const handleCommentSubmit = () => {
    if (!selectedResignation) return;
    
    if (!commentText.trim()) {
      message.warning('请输入评论内容');
      return;
    }

    const currentStepIndex = selectedResignation.approvalProcess.findIndex(step => step.status === 'process');
    if (currentStepIndex === -1) return;

    const newData = approvalData.map(item => 
      item.key === selectedResignation.key ? { 
        ...item, 
        approvalProcess: item.approvalProcess.map((step, index) => 
          index === currentStepIndex ? {
            ...step,
            comments: [
              ...step.comments,
              {
                author: '当前用户',
                avatar: <Avatar icon={<UserOutlined />} />,
                content: <p>{commentText}</p>,
                datetime: new Date().toLocaleString(),
                attachments: fileList.map(file => ({
                  name: file.name,
                  url: '#'
                }))
              }
            ]
          } : step
        )
      } : item
    );
    
    setApprovalData(newData);
    setSelectedResignation(newData.find(item => item.key === selectedResignation.key));
    setCommentText('');
    setFileList([]);
    message.success('评论已提交');
  };

  const columns = [
    {
      title: '员工姓名',
      dataIndex: 'employeeName',
      key: 'employeeName',
      render: (text, record) => (
        <a onClick={() => showDetail(record)}>{text}</a>
      )
    },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department'
    },
    {
      title: '职位',
      dataIndex: 'position',
      key: 'position'
    },
    {
      title: '申请日期',
      dataIndex: 'applyDate',
      key: 'applyDate'
    },
    {
      title: '最后工作日',
      dataIndex: 'lastWorkingDay',
      key: 'lastWorkingDay'
    },
    {
      title: '审批状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        let color = '';
        let text = '';
        switch (status) {
          case 'approved':
            color = 'green';
            text = '已通过';
            break;
          case 'rejected':
            color = 'red';
            text = '已驳回';
            break;
          default:
            color = 'orange';
            text = '待审批';
        }
        return <Tag color={color}>{text}</Tag>;
      }
    }
  ];

  // 根据当前激活的标签页选择显示的数据
  const getTableData = () => {
    switch (activeTab) {
      case 'pending':
        return pendingResignations;
      case 'processed':
        return processedResignations;
      case 'myInitiated':
        return myInitiatedResignations;
      default:
        return approvalData;
    }
  };

  const uploadProps = {
    onRemove: file => {
      const index = fileList.indexOf(file);
      const newFileList = fileList.slice();
      newFileList.splice(index, 1);
      setFileList(newFileList);
    },
    beforeUpload: file => {
      setFileList([...fileList, file]);
      return false;
    },
    fileList,
  };

  // 检查当前用户是否是当前审批环节的处理人
  const isCurrentApprover = (selectedResignation) => {
    if (!selectedResignation) return false;
    const currentStep = selectedResignation.approvalProcess.find(step => step.status === 'process');
    return currentStep && currentStep.description.includes('朱泽名'); // 假设当前用户是朱泽名
  };

  return (
    <div style={{ backgroundColor: '#f5f5f5', minHeight: '100vh', padding: 16 }}>
      {/* 顶部卡片式Tab */}
      <Card style={{ marginBottom: 16 }}>
        <Tabs 
          type="card" 
          activeKey={activeTab} 
          onChange={setActiveTab}
        >
          <TabPane 
            tab={
              <span>
                <AuditOutlined />
                待处理的 ({pendingResignations.length})
              </span>
            } 
            key="pending"
          />
          <TabPane 
            tab={
              <span>
                <CheckOutlined />
                已处理的
              </span>
            } 
            key="processed"
          />
          <TabPane 
            tab={
              <span>
                <UserOutlined />
                我发起的
              </span>
            } 
            key="myInitiated"
          />
        </Tabs>

      <div style={{ display: 'flex', gap: 16 }}>
        {/* 左侧离职申请列表 */}
        <div style={{ width: 380, flexShrink: 0 }}>
          <Card 
            title="离职申请列表"
            bordered={false}
            style={{ boxShadow: '0 1px 3px rgba(0,0,0,0.1)', height: '100%' }}
          >
            <div style={{ overflowY: 'auto', height: 'calc(100vh - 220px)' }}>
              {getTableData().map(resignation => (
                <Card 
                  key={resignation.key}
                  style={{ 
                    marginBottom: 16, 
                    cursor: 'pointer',
                    borderLeft: selectedResignation?.key === resignation.key ? '3px solid #1890ff' : '1px solid #f0f0f0'
                  }}
                  onClick={() => showDetail(resignation)}
                >
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <div>
                      <h4 style={{ marginBottom: 8 }}>{resignation.employeeName}</h4>
                      <div style={{ color: '#666', fontSize: 12 }}>{resignation.department} - {resignation.position}</div>
                    </div>
                    <Tag color={resignation.status === 'pending' ? 'orange' : resignation.status === 'approved' ? 'green' : 'red'}>
                      {resignation.status === 'pending' ? '待审批' : resignation.status === 'approved' ? '已通过' : '已驳回'}
                    </Tag>
                  </div>
                  <Divider style={{ margin: '12px 0' }} />
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <div>
                      <div style={{ color: '#666', fontSize: 12 }}>申请日期</div>
                      <div>{resignation.applyDate}</div>
                    </div>
                    <div>
                      <div style={{ color: '#666', fontSize: 12 }}>最后工作日</div>
                      <div>{resignation.lastWorkingDay}</div>
                    </div>
                  </div>
                </Card>
              ))}
            </div>
          </Card>
        </div>

        {/* 右侧审批内容 - 主要区域 */}
        <div style={{ flex: 1 }}>
          {selectedResignation ? (
            <Card 
              title={`${selectedResignation.employeeName}的离职申请`}
              bordered={false}
              style={{ boxShadow: '0 1px 3px rgba(0,0,0,0.1)', height: '100%' }}
              extra={
                <Space>
                  <Tag color={selectedResignation.status === 'pending' ? 'orange' : selectedResignation.status === 'approved' ? 'green' : 'red'}>
                    {selectedResignation.status === 'pending' ? '等待朱泽名处理' : selectedResignation.status === 'approved' ? '已通过' : '已驳回'}
                  </Tag>
                  {selectedResignation.status === 'pending' && isCurrentApprover(selectedResignation) && (
                    <Space>
                      <Button 
                        type="primary" 
                        icon={<CheckOutlined />} 
                        onClick={handleApprove}
                      >
                        通过
                      </Button>
                      <Button 
                        danger 
                        icon={<CloseOutlined />} 
                        onClick={handleReject}
                      >
                        驳回
                      </Button>
                    </Space>
                  )}
                </Space>
              }
            >
              <div style={{ display: 'flex', gap: 24, height: 'calc(100vh - 220px)', overflowY: 'auto' }}>
                {/* 左侧离职详情 */}
                <div style={{ flex: 1 }}>
                  <h3>基本信息</h3>
                  <div style={{ display: 'grid', gridTemplateColumns: '100px 1fr', gap: '12px 0', alignItems: 'center' }}>
                    <div style={{ fontWeight: 'bold', color: '#666' }}>员工姓名</div>
                    <div>{selectedResignation.employeeName}</div>
                    
                    <div style={{ fontWeight: 'bold', color: '#666' }}>所属部门</div>
                    <div>{selectedResignation.department}</div>
                    
                    <div style={{ fontWeight: 'bold', color: '#666' }}>职位</div>
                    <div>{selectedResignation.position}</div>
                    
                    <div style={{ fontWeight: 'bold', color: '#666' }}>申请日期</div>
                    <div>{selectedResignation.applyDate}</div>
                    
                    <div style={{ fontWeight: 'bold', color: '#666' }}>最后工作日</div>
                    <div>{selectedResignation.lastWorkingDay}</div>
                  </div>
                  
                  <Divider />
                  
                  <h3>离职原因</h3>
                  <div style={{ padding: '12px', backgroundColor: '#f9f9f9', borderRadius: 4 }}>
                    {selectedResignation.reason}
                  </div>
                  
                  <Divider />
                  
                  <h3>工作交接计划</h3>
                  <div style={{ padding: '12px', backgroundColor: '#f9f9f9', borderRadius: 4 }}>
                    {selectedResignation.handoverPlan}
                  </div>
                </div>
                
                {/* 右侧审批流程 */}
                <div style={{ width: 500 }}>
                  <h3>审批流程</h3>
                  <Steps 
                    direction="vertical" 
                    size="small" 
                    current={selectedResignation.approvalProcess.findIndex(step => step.status === 'process')}
                    items={selectedResignation.approvalProcess.map(step => ({
                      title: step.title,
                      description: (
                        <div>
                          <div>{step.description}</div>
                          {step.date && <div style={{ color: '#999', fontSize: 12 }}>{step.date}</div>}
                        </div>
                      ),
                      status: step.status,
                      subTitle: step.comments.length > 0 && (
                        <div style={{ marginTop: 8 }}>
                          <div style={{ fontWeight: 'bold', marginBottom: 8 }}>审批意见:</div>
                          {step.comments.map((comment, idx) => (
                            <Comment
                              key={idx}
                              author={comment.author}
                              avatar={comment.avatar}
                              content={comment.content}
                              datetime={comment.datetime}
                              actions={comment.attachments?.length > 0 ? [
                                <Space>
                                  {comment.attachments.map((file, i) => (
                                    <a key={i} href={file.url} target="_blank" rel="noopener noreferrer">
                                      {file.name}
                                    </a>
                                  ))}
                                </Space>
                              ] : null}
                            />
                          ))}
                        </div>
                      )
                    }))}
                  />
                  
                  {/* 当前审批环节的评论输入框 */}
                  {selectedResignation.status === 'pending' && isCurrentApprover(selectedResignation) && (
                    <>
                      <Divider />
                      <h3>发表审批意见</h3>
                      <TextArea 
                        rows={4} 
                        placeholder="请输入审批意见..." 
                        value={commentText}
                        onChange={e => setCommentText(e.target.value)}
                        style={{ marginBottom: 16 }}
                      />
                      
                      <Upload {...uploadProps}>
                        <Button icon={<UploadOutlined />}>上传附件</Button>
                      </Upload>
                      
                      <div style={{ marginTop: 16, display: 'flex', justifyContent: 'flex-end' }}>
                        <Button 
                          type="primary" 
                          icon={<SendOutlined />} 
                          onClick={handleCommentSubmit}
                        >
                          提交意见
                        </Button>
                      </div>
                    </>
                  )}
                </div>
              </div>
            </Card>
          ) : (
            <Card 
              bordered={false}
              style={{ 
                boxShadow: '0 1px 3px rgba(0,0,0,0.1)', 
                height: '100%',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center'
              }}
            >
              <div style={{ textAlign: 'center', color: '#999' }}>
                <AuditOutlined style={{ fontSize: 48, marginBottom: 16 }} />
                <div>请从左侧列表选择一个离职申请</div>
              </div>
            </Card>
          )}
        </div>
      </div>
      </Card>
    </div>
  );
};

export default ResignationApproval;